import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useNameStore = defineStore('name', () => {
  const userInput = ref({
    birthDate: '',
    birthTime: '',
    isMultipleBirth: false,
    multipleCount: 2,
    genders: '',
    surname: '',
    avoidWords: ''
  })

  // 从localStorage读取历史记录和收藏数据
  const generatedNames = ref([])
  const history = ref(JSON.parse(localStorage.getItem('nameHistory') || '[]'))
  const favorites = ref(JSON.parse(localStorage.getItem('nameFavorites') || '[]'))

  // 监听数据变化，保存到localStorage
  watch(history, (newHistory) => {
    localStorage.setItem('nameHistory', JSON.stringify(newHistory))
  }, { deep: true })

  watch(favorites, (newFavorites) => {
    localStorage.setItem('nameFavorites', JSON.stringify(newFavorites))
  }, { deep: true })

  function setUserInput(input) {
    userInput.value = { ...userInput.value, ...input }
  }

  function addToHistory(names) {
    history.value.push({
      id: Date.now(),
      date: new Date().toISOString(),
      input: { ...userInput.value },
      names
    })
  }

  function saveToFavorites(nameGroup) {
    favorites.value.push({
      id: Date.now(),
      date: new Date().toISOString(),
      nameGroup,
      input: { ...userInput.value }
    })
  }

  function clearGeneratedNames() {
    generatedNames.value = []
  }

  function deleteHistory(id) {
    const index = history.value.findIndex(item => item.id === id)
    if (index !== -1) {
      history.value.splice(index, 1)
    }
  }

  function deleteFavorite(id) {
    const index = favorites.value.findIndex(item => item.id === id)
    if (index !== -1) {
      favorites.value.splice(index, 1)
    }
  }

  // 导出历史记录数据
  function exportHistory() {
    const dataStr = JSON.stringify(history.value, null, 2)
    return dataStr
  }
  
  // 导出收藏数据
  function exportFavorites() {
    const dataStr = JSON.stringify(favorites.value, null, 2)
    return dataStr
  }
  
  // 导出所有数据
  function exportAllData() {
    const data = {
      history: history.value,
      favorites: favorites.value,
      exportDate: new Date().toISOString()
    }
    const dataStr = JSON.stringify(data, null, 2)
    return dataStr
  }

  return {
    userInput,
    generatedNames,
    history,
    favorites,
    setUserInput,
    addToHistory,
    saveToFavorites,
    clearGeneratedNames,
    deleteHistory,
    deleteFavorite,
    exportHistory,
    exportFavorites,
    exportAllData
  }
}) 